package com.nobuyme.box.util;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import android.os.IBinder;
import android.text.TextUtils;
import android.text.format.Time;
import android.util.Log;

import com.nobuyme.box.account.Account;
import com.nobuyme.box.account.AccountManager;
import com.nobuyme.box.app.UrlCenter;
import com.nobuyme.box.bean.BoxPollingEntity;
import com.nobuyme.box.bean.GetIndex;
import com.nobuyme.box.bean.InitIdEntity;
import com.nobuyme.box.bean.UpdataEntity;
import com.nobuyme.box.bean.UpdataStateEvent;
import com.nobuyme.box.downUpdata.AppUpdateThread;
import com.nobuyme.box.toy.ManageHomeActivity;
import com.nobuyme.box.toy.ReturnSuccessActivity;
import com.nobuyme.box.toy.SuccessActivity;
import com.nobuyme.box.toy.manage.PutGoodsActivity;
import com.pachong.android.framework.httprequest.HttpRequest;
import com.pachong.android.framework.httprequest.ResponseParser;
import com.pachong.android.framework.httprequest.UrlParams;
import com.pachong.android.framework.httprequest.responsecallbacks.DataRequestListener;
import com.pachong.android.frameworkbase.utils.EasyToast;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import static com.nobuyme.box.downUpdata.AppUpdateThread.rebootSU;


/**
 * Created by Yong.
 * E-mail：775811790@qq.com
 * 2017/8/7
 */


public class PollingService extends Service {
    public static final String ACTION = "com.nobuyme.box.util.PollingService";
    final static String LOCAL_APK_NAME = Environment.getExternalStorageDirectory().getAbsolutePath() +
            File.separator + "apkName.apk";
    private File file;
    private int count = 0;
    private String link;
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        Log.e("New message152","New message");
//        new PollingThread().start();
    }

    @Override
    public void onStart(Intent intent, int startId) {
        Log.e("New message1455","New message");
        new PollingThread().start();
    }



    /**
     * Polling thread
     * 模拟向Server轮询的异步线程
     * @Author Ryan
     * @Create 2013-7-13 上午10:18:34
     */

    class PollingThread extends Thread {
        @Override
        public void run() {
//            设置每隔4秒轮询一次

//           for (int i = 0; i < 14; i++){
//                try {
//                    Thread.sleep(4000);
//                    Log.e("New message","New message"+i);
                    setState();
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//            }
//            }
        }

        private void setState() {
            Account acc = AccountManager.getCurrentAccount();
            int id = acc.getId();
            HttpRequest request = new HttpRequest(getBaseContext());
            String urlAll = String.format(UrlCenter.BOX_POLLING,id);
            UrlParams urlParams = new UrlParams();
            urlParams.put("toyboxId",id+"");
            request.get(urlAll, urlParams, new DataRequestListener<BoxPollingEntity>(BoxPollingEntity.class) {
                @Override
                public void onStart(Context context, String url) {
                    super.onStart(context, url);
                }
                @Override
                public void onSuccess(BoxPollingEntity o) {
                    super.onSuccess(o);
                    if(AccountManager.getCurrentAccount().getIs_login()==false) {
                        if (o.getAdmin_status() == 0) {
                            //0表示未登录，非0 表示已登录
                        }else{
                            ManageHomeActivity.start(getApplicationContext());
//                            ToyManageListActivity.start(getApplicationContext());
                            AccountManager.getCurrentAccount().setIs_login(true);
                        }
                    }
                    if(o.getLattice_id()==0){
                    }else{
                        //租赁成功
                        if(o.getLattice_type()==0){
                            setOpenSuccess(o.getLattice_id(),0,0);
                            return;
                        }else if(o.getLattice_type()==1){
                          //归还.
                         setOpenSuccess(o.getLattice_id(),1,0);
                            return;
                        }else if(o.getLattice_type()==4){
                            setOpenSuccess(o.getLattice_id(),4,4);
                        }
                        else{
//                            EasyToast.showToast(getApplicationContext(),"获取到别的"+o.getLattice_type());
                        }
                    }
                    if(o.getGoods_id()==-1){
                        //当商品不在配送单是返回的-----PutGoodsActivity
                        EasyToast.showToast(getApplicationContext(),"不在配送单");
                        EventBus.getDefault().post(new UpdataStateEvent(-1,0+"",0+"",0));
                    }else if(o.getGoods_id()==0){
                    }else{
                        if(o.getGoods().getName()!=null){
                            //当管理员扫描到商品时
                        EventBus.getDefault().post(new UpdataStateEvent(1,o.getGoods().getName(),o.getGoods().getCover(),o.getGoods().getId()));
                        }
                    }
                    //更新apk
                    UpDataApk();
                }
                @Override
                public void onFailure(Throwable t, int errorNo, String strMsg) {
                    super.onFailure(t, errorNo, strMsg);
                    EasyToast.showToast(getApplicationContext(),"轮询失败");
                }
            });

        }



                //开柜
                    private void setOpenSuccess(final int lattice_id,final int type,int sellType) {
                    Account acc= AccountManager.getCurrentAccount();
                    HttpRequest req = new HttpRequest(getApplicationContext());
                    String urlAll =String.format(UrlCenter.BOX_OPEN,acc.getId(),lattice_id,sellType);
                        req.put(urlAll, null, new DataRequestListener<Object>(Object.class) {
                            @Override
                            public void onStart(Context context, String url) {
                                super.onStart(context, url);
                            }
                            @Override
                            public void onSuccess(Object o) {
                                super.onSuccess(o);
                                getOpenPosition(lattice_id,type);
                            }

                            @Override
                            public void onFailure(Throwable t, int errorNo, String strMsg) {
                                super.onFailure(t, errorNo, strMsg);
                            }
                        });
                }
        }



    public void getOpenPosition(final int lattice_id, final int type){
             HttpRequest request = new HttpRequest(this);
             UrlParams params = new UrlParams();
             params.put("lattice_id",lattice_id+"");
             String urlAll =String.format(UrlCenter.GETINDEX,lattice_id);
             request.get(urlAll, null, new DataRequestListener<GetIndex>(GetIndex.class) {
                 @Override
                 public void onStart(Context context, String url) {
                     super.onStart(context, url);
                 }
                 @Override
                 public void onSuccess(GetIndex o) {
                     super.onSuccess(o);
                             if(type==0){
                                 //租赁成功的时候第一次开柜
                                 Account acc = AccountManager.getCurrentAccount();
                                 PutGoodsActivity.openLattice(acc.getId(),acc.getPolling_one(),acc.getPolling_two(),acc.getPolling_three(),acc.getPolling_four(),o.getPosition());
                                 SuccessActivity.start(getApplicationContext(),o.getPosition());
                             }else if(type==1){
                                 //归还成功的时候第一次开柜
                                 Account acc = AccountManager.getCurrentAccount();
                                 PutGoodsActivity.openLattice(acc.getId(),acc.getPolling_one(),acc.getPolling_two(),acc.getPolling_three(),acc.getPolling_four(),o.getPosition());
                                 ReturnSuccessActivity.start(getApplicationContext(),o.getPosition());
                     }else if(type==4){
                                 Account acc = AccountManager.getCurrentAccount();
                                 PutGoodsActivity.openLattice(acc.getId(),acc.getPolling_one(),acc.getPolling_two(),acc.getPolling_three(),acc.getPolling_four(),o.getPosition());
                             }
                 }
                 @Override
                 public void onFailure(Throwable t, int errorNo, String strMsg) {
                     super.onFailure(t, errorNo, strMsg);
                     EasyToast.showToast(getApplicationContext(),"设置索引失败"+lattice_id);
                 }
             });
    }


    //自动更新
    private void UpDataApk() {
        Time t=new Time(); // or Time t=new Time("GMT+8"); 加上Time Zone资料
        t.setToNow(); // 取得系统时间。
        int mHour = t.hour;    // 0-23
        int mMinuts = t.minute;
        //提前设置好自动更新，保证3点能进去
        if(mHour==2&&mMinuts>=8&&mMinuts<9){
            //设置下true 避免一直进来
            AccountManager.getCurrentAccount().setIs_updata(false);
            count=0;
        }
        if(AccountManager.getCurrentAccount().getIs_updata()==false){
            //设置凌晨3点更新
            if(mHour==3&&mMinuts>=1&&mMinuts<2){
                HttpRequest request = new HttpRequest(getApplicationContext());
                request.get(UrlCenter.USER_UPDATA, null, new DataRequestListener<UpdataEntity>(UpdataEntity.class) {
                    @Override
                    public void onStart(Context context, String url) {
                        super.onStart(context, url);
                    }
                    @Override
                    public void onSuccess(UpdataEntity o) {
                        super.onSuccess(o);
                        final String updataContent = o.toString();
                        String downLink = o.getLink();
                        //判断是否跟保存一直 一样就不进了，不一样进方法
                        if(!getInnerPath().equals(o.getLink())&&count==0){
//                            EasyToast.showToast(getApplicationContext(),"今日有更新");
                            count++;
                            //设置下true 避免一直进来
                            AccountManager.getCurrentAccount().setIs_updata(true);
//                            EasyToast.showToast(getApplicationContext(), PollingService.this.link);
                            AppUpdateThread.startDownloade(downLink, downLink, LOCAL_APK_NAME, new AppUpdateThread.OnProgressListener() {
                            @Override
                            public void onSuccess(boolean isSuccess) {
                                if (isSuccess == false){
                                    AccountManager.getCurrentAccount().setIs_updata(false);
                                }else if (isSuccess) {
                                    //下载成功了，准备安装
                                    new Thread(new Runnable() {
                                        @Override
                                        public void run() {
                                            save(updataContent);
                                            AppUpdateThread.silentInstall(LOCAL_APK_NAME);
                                            rebootSU();
                                        }
                                    }).start();
                                };
                            }
                        });
                        }
                    }
                    @Override
                    public void onFailure(Throwable t, int errorNo, String strMsg) {
                        super.onFailure(t, errorNo, strMsg);
                        //设置下true 避免一直进来
                        AccountManager.getCurrentAccount().setIs_updata(false);
                    }
                });
            }
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        System.out.println("Service:onDestroy");
    }

    /**
     * 获取内置SD卡路径
     *
     * @return
     */
    public String getInnerSDCardPath() {
        return Environment.getExternalStorageDirectory().getPath();
    }


    //读取文本内容
    private String getInnerPath() {
        StringBuilder log = new StringBuilder();
        String inPath = getInnerSDCardPath();
        log.append("内置SD卡路径：" + inPath + "\r\n");
        String allPath = inPath + "/initdata/updata.txt";
        Log.e("内置SD卡路径", allPath);
        //打开文件
        file = new File(allPath);
        //如果path是传递过来的参数，可以做一个非目录的判断
        if (file.isDirectory()) {
            Log.e("TestFile", "未找到初始化文件");
        } else {
            try {
                InputStream instream = new FileInputStream(file);
                if (instream != null) {
                    InputStreamReader inputreader = new InputStreamReader(instream);
                    BufferedReader buffreader = new BufferedReader(inputreader);
                    String line;
                    //分行读取
                    try {
                        String content = ""; //文件内容字符串
                        while ((line = buffreader.readLine()) != null) {
                            content += line + "\n";
                            //从配置文件保存toyBox信息
                            if (TextUtils.isEmpty(content)) {
                                EasyToast.showToast(this, "初始化文件为空");
                            } else {
                                ResponseParser parser = new ResponseParser(InitIdEntity.class);
                                parser.setJsonString(content.trim());
                                try {
                                    JSONObject jsonObject = new JSONObject(content.trim());
                                    link = (String) jsonObject.get("link");
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }


                            }
                        }
                        instream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                        Log.e("TestFile", e.getMessage());
                    }
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                EasyToast.showToast(this, "未找到初始化文件");
            }
        }
        return link;
    }
    //保存文本内容

    private void save(String link){
        try {
      /* 根据用户提供的文件名，以及文件的应用模式，打开一个输出流.文件不存系统会为你创建一个的，
       * 至于为什么这个地方还有FileNotFoundException抛出，我也比较纳闷。在Context中是这样定义的
       *  public abstract FileOutputStream openFileOutput(String name, int mode)
       *  throws FileNotFoundException;
       * openFileOutput(String name, int mode);
       * 第一个参数，代表文件名称，注意这里的文件名称不能包括任何的/或者/这种分隔符，只能是文件名
       *     该文件会被保存在/data/data/应用名称/files/chenzheng_java.txt
       * 第二个参数，代表文件的操作模式
       *     MODE_PRIVATE 私有（只能创建它的应用访问） 重复写入时会文件覆盖
       *     MODE_APPEND 私有  重复写入时会在文件的末尾进行追加，而不是覆盖掉原来的文件
       *     MODE_WORLD_READABLE 公用 可读
       *     MODE_WORLD_WRITEABLE 公用 可读写
       * */
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(link.getBytes());
            fos.flush();
            fos.close();
//            Toast.makeText(getApplicationContext(), "保存成功", Toast.LENGTH_LONG).show();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}




